﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Communication.Help.Crc;

public static class Crc16Modbus
{
    private const ushort Init = 0xFFFF;
    private static readonly ushort[] Table = Crc16Utils.GenerateTable(0xA001, true);

    public static ushort Compute(IEnumerable<byte> data)
    {
        return data.Aggregate(Init, static (current, b) => (ushort)((current >> 8) ^ Table[(current ^ b) & 0xFF]));
    }

    public static ushort Compute(ReadOnlySpan<byte> data)
    {
        var crc = Init;
        foreach (var b in data)
            crc = (ushort)((crc >> 8) ^ Table[(crc ^ b) & 0xFF]);
        return crc;
    }
}